<template>
  <div class="visualization">
    <el-row :gutter="16" class="overview-row">
      <!-- 数据概览卡片 -->
      <el-col :span="24" :sm="12" :md="6">
        <div class="overview-card online-devices">
          <div class="card-icon">
            <el-icon size="24" color="#409EFF"><Monitor /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">在线设备</div>
            <div class="card-value">24</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="overview-card today-data">
          <div class="card-icon">
            <el-icon size="24" color="#67C23A"><DataLine /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">今日数据</div>
            <div class="card-value">1,256</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="overview-card alerts">
          <div class="card-icon">
            <el-icon size="24" color="#E6A23C"><Warning /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">异常告警</div>
            <div class="card-value">3</div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="24" :sm="12" :md="6">
        <div class="overview-card quality-rate">
          <div class="card-icon">
            <el-icon size="24" color="#F56C6C"><DataAnalysis /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">水质达标率</div>
            <div class="card-value">98.5%</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top: 16px;">
      <!-- 实时数据图表 -->
      <el-col :span="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>实时水质监测数据</span>
              <div class="header-actions">
                <el-button size="small" @click="refreshData" class="refresh-button">
                  <el-icon><Refresh /></el-icon>
                  <span class="button-text">刷新</span>
                </el-button>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="realtimeChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 设备状态分布 -->
      <el-col :span="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>设备状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="deviceStatusChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top: 16px;">
      <!-- 历史趋势分析 -->
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>历史趋势分析</span>
              <div class="header-actions">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  class="date-picker"
                />
                <el-button size="small" type="primary" @click="handleQuery" style="margin-left: 10px;">
                  查询
                </el-button>
              </div>
            </div>
          </template>
          <div class="chart-container large">
            <div ref="trendChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时数据表格 -->
    <el-card style="margin-top: 16px;">
      <template #header>
        <div class="card-header">
          <span>实时监测数据</span>
          <div class="header-actions">
            <el-button size="small" @click="exportData" class="action-button">
              <el-icon><Download /></el-icon>
              <span class="button-text">导出数据</span>
            </el-button>
            <el-button size="small" @click="openConfig" class="action-button">
              <el-icon><Setting /></el-icon>
              <span class="button-text">配置管理</span>
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="realtimeData" style="width: 100%" v-loading="loading" class="data-table">
        <el-table-column prop="deviceName" label="设备名称" :width="getColumnWidth('deviceName')" />
        <el-table-column prop="parameter" label="监测参数" :width="getColumnWidth('parameter')" />
        <el-table-column prop="value" label="当前值" :width="getColumnWidth('value')" />
        <el-table-column prop="unit" label="单位" :width="getColumnWidth('unit')" />
        <el-table-column prop="status" label="状态" :width="getColumnWidth('status')">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'" class="status-tag">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" :width="getColumnWidth('updateTime')" />
        <el-table-column label="操作" :width="getColumnWidth('actions')">
          <template #default="scope">
            <el-button size="small" @click="viewDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  Monitor, 
  DataLine, 
  Warning, 
  DataLine as DataAnalysis, 
  PieChart, 
  Refresh, 
  Download, 
  Setting 
} from '@element-plus/icons-vue'

// 图表引用
const realtimeChart = ref(null)
const deviceStatusChart = ref(null)
const trendChart = ref(null)

// 图表实例
let realtimeChartInstance = null
let deviceStatusChartInstance = null
let trendChartInstance = null

// 响应式断点
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 获取列宽
const getColumnWidth = (column) => {
  if (isMobile.value) {
    const mobileWidths = {
      deviceName: 100,
      parameter: 80,
      value: 70,
      unit: 60,
      status: 80,
      updateTime: 120,
      actions: 80
    }
    return mobileWidths[column] || 100
  }
  const desktopWidths = {
    deviceName: 150,
    parameter: 120,
    value: 100,
    unit: 80,
    status: 100,
    updateTime: 180,
    actions: 120
  }
  return desktopWidths[column] || 150
}

// 日期范围
const dateRange = ref([])

// 实时数据
const realtimeData = ref([
  {
    deviceName: '水质监测仪A',
    parameter: 'pH值',
    value: '7.2',
    unit: 'pH',
    status: '正常',
    updateTime: '2024-01-15 10:30:00'
  },
  {
    deviceName: '水质监测仪A',
    parameter: '溶解氧',
    value: '8.5',
    unit: 'mg/L',
    status: '正常',
    updateTime: '2024-01-15 10:30:00'
  },
  {
    deviceName: '流量计B',
    parameter: '流量',
    value: '125.6',
    unit: 'm³/s',
    status: '异常',
    updateTime: '2024-01-15 10:25:00'
  },
  {
    deviceName: '压力传感器C',
    parameter: '压力',
    value: '2.3',
    unit: 'MPa',
    status: '正常',
    updateTime: '2024-01-15 10:28:00'
  }
])

const loading = ref(false)

// 生成模拟数据
const generateMockData = () => {
  const now = new Date()
  const hours = []
  const phData = []
  const oxygenData = []
  const temperatureData = []
  
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 60 * 1000)
    hours.push(time.getHours() + ':00')
    
    // 生成模拟的水质数据
    phData.push((Math.random() * 2 + 6.5).toFixed(1))
    oxygenData.push((Math.random() * 3 + 7).toFixed(1))
    temperatureData.push((Math.random() * 10 + 15).toFixed(1))
  }
  
  return { hours, phData, oxygenData, temperatureData }
}

// 初始化实时数据图表
const initRealtimeChart = () => {
  if (!realtimeChart.value) return
  
  realtimeChartInstance = echarts.init(realtimeChart.value)
  
  const { hours, phData, oxygenData, temperatureData } = generateMockData()
  
  const option = {
    title: {
      text: '实时水质监测',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['pH值', '溶解氧', '温度'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: hours
    },
    yAxis: [
      {
        type: 'value',
        name: 'pH值',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '溶解氧(mg/L)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: 'pH值',
        type: 'line',
        data: phData,
        smooth: true,
        lineStyle: {
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '溶解氧',
        type: 'line',
        yAxisIndex: 1,
        data: oxygenData,
        smooth: true,
        lineStyle: {
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '温度',
        type: 'line',
        data: temperatureData,
        smooth: true,
        lineStyle: {
          color: '#E6A23C'
        },
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  realtimeChartInstance.setOption(option)
}

// 初始化设备状态图表
const initDeviceStatusChart = () => {
  if (!deviceStatusChart.value) return
  
  deviceStatusChartInstance = echarts.init(deviceStatusChart.value)
  
  const option = {
    title: {
      text: '设备状态分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 24, name: '在线', itemStyle: { color: '#67C23A' } },
          { value: 3, name: '离线', itemStyle: { color: '#909399' } },
          { value: 2, name: '故障', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  }
  
  deviceStatusChartInstance.setOption(option)
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChart.value) return
  
  trendChartInstance = echarts.init(trendChart.value)
  
  const days = []
  const phTrend = []
  const oxygenTrend = []
  const temperatureTrend = []
  
  for (let i = 29; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    days.push(date.getMonth() + 1 + '/' + date.getDate())
    
    phTrend.push((Math.random() * 2 + 6.5).toFixed(1))
    oxygenTrend.push((Math.random() * 3 + 7).toFixed(1))
    temperatureTrend.push((Math.random() * 10 + 15).toFixed(1))
  }
  
  const option = {
    title: {
      text: '历史趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['pH值', '溶解氧', '温度'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: days
    },
    yAxis: [
      {
        type: 'value',
        name: 'pH值',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '溶解氧(mg/L)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: 'pH值',
        type: 'line',
        data: phTrend,
        smooth: true,
        lineStyle: {
          color: '#409EFF',
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.1)'
            }]
          }
        }
      },
      {
        name: '溶解氧',
        type: 'line',
        yAxisIndex: 1,
        data: oxygenTrend,
        smooth: true,
        lineStyle: {
          color: '#67C23A',
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(103, 194, 58, 0.3)'
            }, {
              offset: 1, color: 'rgba(103, 194, 58, 0.1)'
            }]
          }
        }
      },
      {
        name: '温度',
        type: 'line',
        data: temperatureTrend,
        smooth: true,
        lineStyle: {
          color: '#E6A23C',
          width: 3
        },
        itemStyle: {
          color: '#E6A23C'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(230, 162, 60, 0.3)'
            }, {
              offset: 1, color: 'rgba(230, 162, 60, 0.1)'
            }]
          }
        }
      }
    ]
  }
  
  trendChartInstance.setOption(option)
}

// 方法
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据刷新成功')
    
    // 重新初始化图表
    nextTick(() => {
      initRealtimeChart()
      initDeviceStatusChart()
      initTrendChart()
    })
  }, 1000)
}

const handleQuery = () => {
  ElMessage.info('查询历史数据')
  // 重新初始化趋势图表
  nextTick(() => {
    initTrendChart()
  })
}

const exportData = () => {
  ElMessage.info('导出数据功能')
}

const openConfig = () => {
  ElMessage.info('配置管理功能')
}

const viewDetails = (row) => {
  ElMessage.info(`查看 ${row.deviceName} 的详细信息`)
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  if (realtimeChartInstance) {
    realtimeChartInstance.resize()
  }
  if (deviceStatusChartInstance) {
    deviceStatusChartInstance.resize()
  }
  if (trendChartInstance) {
    trendChartInstance.resize()
  }
}

onMounted(() => {
  nextTick(() => {
    initRealtimeChart()
    initDeviceStatusChart()
    initTrendChart()
  })
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  if (realtimeChartInstance) {
    realtimeChartInstance.dispose()
  }
  if (deviceStatusChartInstance) {
    deviceStatusChartInstance.dispose()
  }
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
})
</script>

<style scoped>
.visualization {
  padding: 0;
  background: transparent;
  min-height: calc(100vh - 120px);
}

.overview-row {
  margin-bottom: 0;
}

.overview-card {
  margin-bottom: 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  height: 100px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background: #ffffff;
  border: 1px solid #ebeef5;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
}

.online-devices {
  border-left: 4px solid #409EFF;
}

.today-data {
  border-left: 4px solid #67C23A;
}

.alerts {
  border-left: 4px solid #E6A23C;
}

.quality-rate {
  border-left: 4px solid #F56C6C;
}

.card-icon {
  margin-right: 15px;
  padding: 10px;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 6px;
  font-weight: 400;
}

.card-value {
  font-size: 22px;
  font-weight: 600;
  color: #333333;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
  border: 1px solid #ebeef5;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #ffffff;
  border-bottom: 1px solid #ebeef5;
  flex-wrap: wrap;
  gap: 10px;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333333;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.date-picker {
  width: 280px;
}

.chart-container {
  height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 8px;
  margin: 16px;
}

.chart-container.large {
  height: 350px;
}

.chart {
  width: 100%;
  height: 100%;
}

.data-table {
  margin: 0;
}

.status-tag {
  border-radius: 20px;
  padding: 4px 12px;
}

.refresh-button,
.action-button {
  border-radius: 6px;
}

.button-text {
  margin-left: 5px;
}

:deep(.el-card) {
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
  border: 1px solid #ebeef5;
  overflow: hidden;
}

:deep(.el-card__header) {
  padding: 16px 20px;
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 400;
  padding: 8px 12px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table tr:hover td) {
  background: #f0f9ff;
}

:deep(.el-date-editor) {
  border-radius: 6px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    padding: 0 15px;
    height: 80px;
  }
  
  .card-icon {
    margin-right: 10px;
    padding: 8px;
  }
  
  .card-title {
    font-size: 12px;
    margin-bottom: 4px;
  }
  
  .card-value {
    font-size: 18px;
  }
  
  .card-header {
    padding: 12px 15px;
  }
  
  .card-header span {
    font-size: 14px;
  }
  
  .chart-container {
    height: 220px;
    margin: 12px;
  }
  
  .chart-container.large {
    height: 280px;
  }
  
  .date-picker {
    width: 200px;
  }
  
  .button-text {
    display: none;
  }
  
  .refresh-button .el-icon,
  .action-button .el-icon {
    margin-right: 0;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th) {
    padding: 8px 0;
  }
  
  :deep(.el-table td) {
    padding: 8px 0;
  }
}

@media (max-width: 480px) {
  .overview-card {
    padding: 0 12px;
    height: 70px;
  }
  
  .card-icon {
    padding: 6px;
  }
  
  .card-title {
    font-size: 11px;
  }
  
  .card-value {
    font-size: 16px;
  }
  
  .card-header {
    padding: 10px 12px;
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    margin-top: 10px;
    justify-content: center;
  }
  
  .chart-container {
    height: 180px;
    margin: 10px;
  }
  
  .chart-container.large {
    height: 220px;
  }
  
  .date-picker {
    width: 100%;
  }
  
  :deep(.el-table th) {
    padding: 6px 0;
    font-size: 11px;
  }
  
  :deep(.el-table td) {
    padding: 6px 0;
    font-size: 10px;
  }
  
  :deep(.el-date-editor) {
    width: 100%;
  }
}
</style>